import { Form, Select } from 'antd';
import React, { useEffect, useState } from 'react';

import { FormFieldBase } from '../../../typings/FormFieldBase';

export type SelectFormFieldProps = FormFieldBase & {};
export const SelectFormField: React.FC<SelectFormFieldProps> = (props) => {
  const { name, label, rules, dataSource, placeholder, config, light } = props;
  const [ data, setData ] = useState([]);

  useEffect(() => {
    if(typeof dataSource === 'object'){
      setData(dataSource as any);
    }else if(typeof dataSource === 'function'){
      dataSource()?.then((res: any) => {
        setData(res);
      })
    }
  }, [dataSource]);

  return (
    <Form.Item label={ light ? undefined : label} name={name} rules={rules}>
      <Select placeholder={placeholder} {...config}>
        {(data as any[])?.map((item: any, i: number) => (
          <Select.Option key={i} value={item.value}>
              {item.label}
          </Select.Option>
        ))}
      </Select>
    </Form.Item>
  )
}
